package com.codejoys.monitor.security;

import com.codejoys.monitor.dao.UserDao;
import com.codejoys.monitor.domain.Role;
import com.codejoys.monitor.dto.SysUser;
import com.codejoys.monitor.exception.SysException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SysUserDetailsService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(SysUserDetailsService.class);

    @Autowired
    UserDao userDao;

    // 登录时spring security会自动调用这个方法，去加载用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户登录：{}", username);

        final SysUser user = userDao.findUserByName(username);

        if (user == null) {
            throw new SysException(4001, "登录的用户不存在");
        }

        // 获取角色
        final List<Role> rolesList = user.getRoles();
        String[] roles = null;
        if (rolesList != null && rolesList.size() > 0) {
            roles = new String[rolesList.size()];

            for (int i = 0; i < rolesList.size(); i++) {
                Role role = rolesList.get(i);
                roles[i] = "ROLE_" + role.getKeyword();
            }

            // => ["admin", "teacher"]
        } else {
            roles = new String[] {};
        }

        return User.builder()
                .username(username)
                .password(user.getPassword())
                .authorities(roles)
                .build();
    }
}
